<template>
  <div class="start">
    <div id="score">
      <!-- <span>分数: </span> -->
      <span class="score">0</span>
    </div>

    <!-- .box大盒子 -->
    <div class="bigbox">
      <div class="box">
        <!-- .game游戏区域 -->
        <div class="game"></div>
        <div class="showTip"></div>
      </div>
    </div>

    <div class="toDo">
      <div class="pause">
        <img src="../assets/start/暂停.png" alt="" v-if="mypause">
        <img src="../assets/start/播放.png" alt="" v-if="!mypause">
      </div>
      <div class="button"><img src="../assets/start/刷新.png" alt=""></div>
    </div>
    <div class="showresult" v-if="isOver">
        <div class="box">
          <div class="text">游戏结束,你的分数是 {{score}} 分</div>
          <div class="sure" v-on:click = 'sure'>确定</div>
        </div>
    </div>
    <div class="showresult" v-if="reStart">
        <div class="box">
          <div class="text">游戏已经结束,请点击重新开始</div>
          <div class="sure" v-on:click = 'sure'>确定</div>
        </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
* {
  margin: 0;
  padding: 0;
}

body,
html {
  // background-color: #111b35 !important;
  margin: 0;
  padding: 0;
}

.start {
  // background-color: #111b35 !important;
  box-sizing: border-box;
  position: relative;
  background-color: white;
  .showresult {
      position: absolute;
      background-color: rgba(0, 0, 0, 0.171);
      width: 100%;
      height: 100%;
      top: 0;
      left: 0;
      .box {
        width: 300px;
        padding: 20px;
        height: 170px;
        background: white;
        position: fixed;
        left: 0;
        top: 0;
        right: 0;
        bottom: 0;
        margin: auto;
        border-radius: 5px;
        .text {
          color: #542e61;
          text-align: center;
          margin-top: 20px;
          font-weight: bold;
          letter-spacing: 4px;
          font-size: 24px;

        }
        .sure {
          color: white;
          margin: 20px auto 0;
          font-weight: bold;
          cursor: pointer;
          background: #542e61;
          padding: 6px 10px;
          border-radius: 5px;
          width: 100px;
          text-align: center;
        }
      }
  }
  #score {
    // margin-left: 50px;
    // border: 1px solid #ccc;
    position: fixed;
    top: 10px;
    width: 100%;
    font-size: 40px;
    font-weight: 600;
    text-align: center;
    z-index: 101;
    text-shadow: 2px 2px 4px #fff;
    color: rgb(221, 139, 139);
    margin-top: 3px;
    
  }
  .bigbox {
    // width: 850px;
    height: 100%;
    background-size: 110%;
    background-position: -38px -241px;
    margin: auto;
    // padding-left: 9px;
    box-sizing: border-box;
  }
  .box {
    // width: 800px;
    height: 100%;
    // margin-left: 50px;
    // margin-top: 50px;
    margin: 0 auto;

    box-sizing: border-box;
    /* 父相 */
    position: relative;
    /* 溢出隐藏 */
    overflow: hidden;
    .game {
      /* 子绝 */
      position: absolute;
      top: -150px;
      // left: 29px;
      display: none;
      .row {
        overflow: hidden;
        div {
          width: 98px;
          height: 98px;
          border: 1px solid transparent;
          float: left;
          .black {
            background: black;
          }
        }
      }
    }
    .showTip {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      margin: auto;
      width: 200px;
      height: 200px;
      line-height: 200px;
      text-align: center;
      font-size: 30px;
      font-weight: bolder;
      z-index: 100;
      color: rgb(221, 139, 139);
      text-shadow: -2px -2px 4px #fff;
      /* background-color: rgba(0, 0, 0, 0.1); */
      display: none;
    }
    .showTip.active {
      animation: scale 1s infinite;
    }
  }
  .toDo {
    // display: flex;
    position: fixed;
    top: 16px;
    width: 100%;
    margin: auto;
    // max-width: 1200px;
    // min-width: 800px;
    justify-content: space-between;
    z-index: 102;
    .button,
    .pause {
      // width: 250px;
      position: absolute;
      font-size: 26px;
      cursor: pointer;
      letter-spacing: 4px;
      text-shadow: 1px 1px 3px rgb(161, 161, 161);
      // height: 100px;
      // line-height: 80px;
      text-align: center;
      background-repeat: no-repeat;
      background-size: 95%;
      color: rgb(221, 221, 221);
      font-weight: 600;
      img{
        display: block;
        width: 30px;
        height: 30px;
        background-color: #fff;
        border-radius: 50%;
        margin: 10px 12px;
      }
    }
    .button{
      right: 10px;
    }
    .pause{
      left : 10px;
    }
    :hover {
      text-shadow: 1px 1px 4px rgb(216, 167, 44);
      color: rgb(255, 223, 41);
    }
  }
}

@keyframes scale {
  from {
    font-size: 30px;
  }

  to {
    font-size: 80px;
  }
}
</style>

<script>
// import myScore from '@/assets/arcadeScore.json';
export default {
  // 思路
  // 1. 让.game游戏区动画不断的下落(定时器改变top值)
  // 2. 当.game触底的时候(top值为0的时候), 需要添加新的一行在最前面( insertBefore ),并且每一行里面的黑块是随机出现
  // 3. 删除多余行(已经整行超过.box之外的)
  // 4. 白块黑块都需要可以被点击; 白块被点击游戏结束,停止下落;  黑块被点击,变白,加1分
  // 5. 当游戏触底的时候,最后一行存在黑块未被点击,游戏结束,停止下落
  // 6. 为了增加游戏的趣味性, 分数每增加5分, 速度就加快

  // 封装获取dom对象的函数
  data() {
    return {
      isOver: false,
      reStart : false,
      myArcadeScore : [],
      myName : '',
      score : 0,
      mypause : true,
    };
  },
  created(){
    if(localStorage.getItem('myArcadeScore')){
      this.myArcadeScore = JSON.parse(localStorage.getItem('myArcadeScore'))
    }else{
     this.myArcadeScore = [];
    }
    if(localStorage.getItem('logining') == 'true'){
      this.myName = localStorage.getItem('myname');
    }else{
      this.myName = '';
    }

    // console.log('登录状态==>',localStorage.getItem('logining'));
    // console.log('登录用户==>',this.myName);
  },
  mounted() {

    let myTimeout = setTimeout(() => {
      gameStart();
    }, 500);
    function $(cssSelector) {
      var obj = document.querySelectorAll(cssSelector);

      if (obj.length == 1) {
        return obj[0];
      }

      return obj;
    }

    // 封装一个可以得到指定范围整数的随机函数
    function getRandom(min, max) {
      return Math.floor(Math.random() * (max - min + 1) + min);
    }

    // 1. 让.game游戏区动画不断的下落(定时器改变top值)
    // game游戏区域对应的dom对象
    var game = $(".game");
    // 下落速度
    var speed = 2;
    // 分数文本框
    var scoreDiv = $(".score");
    // 初始分数
    var score = 0;
    // 定时器标识符
    var timer = null;
    // 定义一个变量,保存当前游戏状态, 布尔值  false表示游戏未结束  true游戏结束
    var isOver = false;

    var ispause = false;

    var isStart = false;

    let _this = this;

    let width = window.innerWidth;

    let height = window.innerHeight;

    document.querySelector('.start').style.height = height + 'px';

    // 开启定时器,实现游戏区域下落
    var startGame = function () {
      timer = window.setInterval(function () {
        // 改变top值
        game.style.top = parseInt(game.style.top) + speed + "px";

        // 2. 当.game触底的时候(top值为0的时候), 需要添加新的一行在最前面( insertBefore ),并且每一行里面的黑块是随机出现
        if (parseInt(game.style.top) >= 0) {
          // 判断是否触底
          createDiv();
          // 再次设置game的top值为-100px
          game.style.top = `-${height/5}px`;

          // 3. 删除多余行(已经整行超过.box之外的)
          if (game.children.length > 6) {
            // 判断game的子元素长度是否超过6,因为最多能看到的就是6行
            // 删除最后一行
            game.lastElementChild.remove();
          }

          // 5. 当游戏触底的时候,最后一行存在黑块未被点击,游戏结束,停止下落
          if (game.lastElementChild.getAttribute("data-pass") === null) {
            // 游戏结束
            // alert("游戏结束");
            _this.isOver = true;
            _this.score = score;
            _this.myLocal()
            // 停止下落
            window.clearInterval(timer);
            // 改变游戏状态
            isOver = true;
          }
        }
      }, 20);
    };

    function createDiv() {
      // 创建新的一行
      var newRow = document.createElement("div");
      // 设置类名
      newRow.className = "row";
      // 得到一个1~4之间的随机整数
      var randomNum = getRandom(1, 4);
      // 生成4个列
      for (var i = 1; i <= 4; i++) {
        // 创建新的一列
        var newCol = document.createElement("div");

        newCol.style.width = `${width/4}px`;
        newCol.style.height = `${height/5}px`;
        newCol.style.border = "1px solid gray";
        newCol.style.float = "left";
        newCol.style.background = "white";
        newCol.style.boxSizing = 'border-box';
        if (randomNum == i) {
          // 如果随机整数
          // 添加.black类名, 成为黑块
          newCol.classList.add("black");
          newCol.style.background = "black";
        }
        // 把列加到行里面
        newRow.appendChild(newCol);
      }
      // 把新的一行,添加新的一行在最前面
      game.insertBefore(newRow, game.firstElementChild);
      //   console.log(game)
      myrender();
    }

    var timeid = null;
    var time = 3;
    var timeout = null;
    document.querySelector(".button").onclick = gameStart;
    function gameStart() {
      if (!timeid) {
        time = 3;
        let tip = document.querySelector(".showTip");
        tip.innerHTML = time;
        game.style.display = "none";
        game.style.top = "-150px";
        tip.style.display = "block";
        tip.classList.add("active");
        tip.style.fontSize = '60px'
        isOver = false;
        score = 0;
        scoreDiv.innerHTML = score;
        game.innerHTML = "";
        window.clearInterval(timer);
        speed = 2;
        // document.querySelector(".pause").innerHTML = "暂停";
        _this.mypause = true;
        _this.isOver = false;
        _this.reStart = false;
        ispause = false;
        isStart = false;
        timeid = setInterval(() => {
          time--;
          if (time == 0) {
            tip.innerHTML = "开始";
          } else if (time < 0) {
            window.clearInterval(timeid);
            timeid = null;
            tip.style.display = "none";
            tip.classList.remove("active");
            game.style.display = "block";
            isStart = true;
            for (let i = 0; i < 5; i++) {
              createDiv();
            }
            myrender();
            startGame();
          } else {
            tip.innerHTML = time;
          }
        }, 1000);
      }
    }

    document.querySelector(".pause").onclick = function () {
      if (!isOver) {
        let tip = document.querySelector(".showTip");
        if (!ispause && isStart) {
          window.clearInterval(timer);
          // this.innerHTML = "继续";
          _this.mypause = false;
          tip.style.display = "block";
          tip.innerHTML = "已暂停";
          ispause = true;
          isStart = false;
        } else if (ispause && !isStart) {
          time = 3;
          tip.innerHTML = time;
          tip.classList.add("active");
          window.clearInterval(timeout);
          ispause = false;
          timeout = setInterval(() => {
            time--;
            if (time == 0) {
              tip.innerHTML = "开始";
            } else if (time < 0) {
              window.clearInterval(timeout);
              tip.style.display = "none";
              tip.classList.remove("active");
              game.style.display = "block";
              isStart = true;
              tip.classList.remove("active");
              startGame();
            } else {
              tip.innerHTML = time;
            }
          }, 1000);
          _this.mypause = true;
        }
      } else if (isOver) {
        // alert("游戏已经结束,请刷新页面重新开始游戏");
        _this.reStart = true
      }
    };

    // 4. 白块黑块都需要可以被点击; 白块被点击游戏结束,停止下落;  黑块被点击,变白,加1分
    // 使用事件委托
    game.addEventListener('touchstart',function (e) {
      // 获取事件对象

      e = e || window.event;

      if (isOver) {
        // 如果游戏已经结束
        // alert("游戏已经结束,请刷新页面重新开始游戏");
        _this.reStart = true;
      } else {
        // 如果游戏未结束,游戏正在进行中
        if (isStart) {
          // 判断点击的是黑块还是白块
          // console.log(e.target.classList.contains("black"))
          if (e.target.classList.contains("black")) {
            // 如果点击的是黑块
            // let div = document.querySelectorAll('.black');
            // console.log(e.target.dataset.i == 1);
            if (e.target.dataset.i == 1) {
              // console.log(11)
              // 黑块变白(移除.black类名 )
              e.target.classList.remove("black");


              // e.target.style.background = "white";


              let cnum = 0;
              let mytimeout = setInterval(() => {
                cnum += 1;
                // console.log(e.target.style);
                e.target.style.backgroundColor = `rgba(255, 255, 255, ${cnum/10})`;
                if(cnum == 10){
                  window.clearInterval(mytimeout)
                }
                // console.log(cnum);
              }, 50);


              // 当前黑块被点击以后,在它父元素身上设置一个自定义属性 data-pass值为true 表示当前行的黑块已经被点击过了
              e.target.parentNode.setAttribute("data-pass", true);
              // 分数文本框的值加1( 加分 )
              score++; // 自加1
              // 改变文本框的值
              scoreDiv.innerHTML = score;

              if(score <= 24){
                if(score%6 == 0){
                  speed += 0.4;
                }
              }else if(score <= 70){
                if(score%10 == 0){
                  speed += 0.3;
                }
              }else if(score <= 100){
                if(score%15 == 0){
                  speed += 0.2;
                }
              }else if(score > 100){
               if(score%20 == 0){
                  speed += 0.1;
                }
              }
              myrender();
            }
          } else {
            // 如果点击的是白块
            // 提示信息
            // alert("游戏结束");
           _this.isOver = true;
           _this.score = score;

           _this.myLocal();
           
           
            // 停止下落( 停止定时器 )
            window.clearInterval(timer);
            // 改变游戏状态为结束
            isOver = true;
          }
        }
      }
    });
    function myrender() {
      let div = document.querySelectorAll(".black");
      for (let i = 0; i < div.length; i++) {
        // console.log(div[i].dataset);
        div[i].setAttribute("data-i", div.length - i);
      }
    }
  },
  methods:{
    sure(){
      this.isOver = false;
      this.reStart = false;
    },
     myLocal(){
       let _this = this;
        if(localStorage.getItem('logining') == 'true'){
            if(_this.myArcadeScore.length != 0){
                let issame = false;
                let ind = 0;
                _this.myArcadeScore.forEach(function(item,index){
                  if(item.user == _this.myName){
                    issame = true;
                    ind = index;
                  }
                })
                if(issame){
                  if(_this.score > _this.myArcadeScore[ind].score){
                    let obj = {};
                    obj.user = _this.myName;
                    obj.score = _this.score;
                    _this.myArcadeScore[ind] = obj;
                  }
                }else{
                  let obj = {};
                    obj.user = _this.myName;
                    obj.score = _this.score;
                    _this.myArcadeScore.push(obj);
                }
            }else{
              let obj = {};
                  obj.user = localStorage.getItem('myname');
                  obj.score = _this.score;
                  this.myArcadeScore[0] = obj;
            }
            localStorage.setItem('myArcadeScore',JSON.stringify(this.myArcadeScore));
        }
    }
  }
};
</script>